/*
*author: 陈海俊
*time: 2017/12/25
*
* 自定义滑动事件, 屏蔽了浏览器默认的touchmove行为
*
*/

window.touchStartY = null;
window.touchStartX = null;
let swipeUpEvent = document.createEvent('HTMLEvents');
let swipeDownEvent = document.createEvent('HTMLEvents');
let swipeLeftEvent = document.createEvent('HTMLEvents');
let swipeRightEvent = document.createEvent('HTMLEvents');

swipeUpEvent.initEvent('swipeup',true,true);
swipeDownEvent.initEvent('swipedown',true,true);
swipeLeftEvent.initEvent('swipeleft',true,true);
swipeRightEvent.initEvent('swiperight',true,true);

window.addEventListener('touchstart',e=>{
  window.touchStartY = e.touches[0].screenY;
  window.touchStartX = e.touches[0].screenX;
});
window.addEventListener('touchmove',e=>{
  e.preventDefault();
},{passive:false});
window.addEventListener('touchend',e=>{
  let distanceY = e.changedTouches[0].screenY - window.touchStartY;
  let distanceX = e.changedTouches[0].screenX - window.touchStartX;
  if(Math.abs(distanceX) > Math.abs(distanceY)){
    if(distanceX > 50){
      window.dispatchEvent(swipeRightEvent);
    }else if(distanceX < -50){
      window.dispatchEvent(swipeLeftEvent);
    }
  }else{
    if(distanceY > 50){
      window.dispatchEvent(swipeDownEvent);
    }else if(distanceY < -50){
      window.dispatchEvent(swipeUpEvent);
    }
  }
});
